package org.example.springboot3.controller;

import jakarta.annotation.Resource;
import org.example.springboot3.domain.Activities;
import org.example.springboot3.domain.Registrations;
import org.example.springboot3.service.ActivitiesService;
import org.example.springboot3.service.JwtUtilsService;
import org.example.springboot3.service.RegistrationsService;
import org.example.springboot3.service.UsersService;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")//允许跨域访问
@RequestMapping("/activity")
public class ActivityController {
    @Resource
    private ActivitiesService activitiesService;
    @Resource
    private JwtUtilsService jwtUtilsService;
    @Resource
    private RegistrationsService registrationsService;
    @Resource
    private UsersService usersService;

    //获取用户参与的活动信息
    @GetMapping("/getMyJoinedActivities")
    public List<Map<String,String>> getMyJoinedActivities(@RequestHeader("Authorization") String token) {
        token=token.substring(7).trim();
        if(jwtUtilsService.verifyToken(token)) {//验证token是否有效
            List<Map<String,String>> resultList = new ArrayList<>();
            //通过解析用户token获取当前用户ID查询该用户参与的活动列表，遍历获取活动列表添加对应活动的参与人数
            List<String> activityList = registrationsService.getMyActivityList(jwtUtilsService.parseToken(token).getPayload().get("UserID").toString());
            activityList.forEach(activity -> {//遍历用户参与活动的ID
                resultList.add(getActivityMap(activitiesService.getById(activity)));//获取活动信息以及参与活动人数并加入返回的活动信息列表中
            });
            return resultList;
        }
        return null;
    }

    //获取用户创建的活动信息
    @GetMapping("/getActivitiesByOrganizerId")
    public List<Map<String,String>> getActivitiesByOrganizerId(@RequestHeader("Authorization") String token) {
        token=token.substring(7).trim();
        if(jwtUtilsService.verifyToken(token)) {//验证token是否有效
            List<Map<String,String>> resultList = new ArrayList<>();
            //通过解析用户token获取当前用户ID查询该用户创建的活动列表，遍历获取活动列表添加对应活动的参与人数
            activitiesService.getActivitiesByOrganizerId(jwtUtilsService.parseToken(token).getPayload().get("UserID").toString()).forEach(activities -> {
                resultList.add(getActivityMap(activities));
            });
            return resultList;//获取用户创建的活动
        }
        return null;
    }

    //根据ID获取活动信息
    @GetMapping("/getActivityById")
    public Map<String, String> getActivityById(@RequestParam("activityId") String id){
        Activities activities = activitiesService.getById(id);
        Map<String,String> resultMap = getActivityMap(activities);
        resultMap.put("userName",usersService.getById(activities.getOrganizerId()).getUsername());
      return resultMap;
    }

    //获取目前存在的所有活动信息
    @GetMapping("/getAllActivities")
    public List<Map<String,String>> getAllActivities(){
        List<Map<String,String>> resultList = new ArrayList<>();
        activitiesService.list().forEach(activities -> { //遍历获取的所有活动列表添加相应活动的参与人数信息
            if(activities.getAuditStatus().equals("审核通过")) {
            resultList.add(getActivityMap(activities));
            }
        });
        return resultList;
    }

    //创建活动
    @PostMapping("/addActivity")
    public boolean addActivity(@RequestHeader("Authorization") String token, @RequestBody Activities activities){
        token=token.substring(7).trim();
        if(jwtUtilsService.verifyToken(token)) {//验证token是否有效
            activities.setOrganizerId(jwtUtilsService.parseToken(token).getPayload().get("UserID").toString());//解析token获取当前用户ID，将活动组织者设置为当前用户
            activities.setAuditStatus("待审核");//新添加的活动默认为待审核状态
            return activitiesService.save(activities);//执行活动表的插入操作
        }
        return false;
    }

    //参加活动
    @PostMapping("/joinActivity")
    public boolean joinActivity(@RequestHeader("Authorization") String token, @RequestBody Registrations registrations){
        token=token.substring(7).trim();
        if(jwtUtilsService.verifyToken(token)) {//验证token是否有效
            registrations.setUserId(jwtUtilsService.parseToken(token).getPayload().get("UserID").toString());//解析token获取当前用户ID，将参与者设置为当前用户
            return registrationsService.save(registrations);//执行报名表的插入操作
        }
        else return false;
    }

    //根据审核状态获取活动
    @GetMapping("/getActivitiesByAuditStatus")
    public List<Activities> getPendingAuditActivity(@RequestHeader("Authorization") String token, @RequestParam("status") String status){
        token=token.substring(7).trim();
        if(jwtUtilsService.verifyToken(token)) {//验证用户token
            List<Activities> resultList = new ArrayList<>();
            activitiesService.list().forEach(activities -> {
                if(activities.getAuditStatus().equals(status)) //将满足要求的活动加入返回的信息列表
                    resultList.add(activities);
            });
            return resultList;
        }
        else return null;
    }

    //根据活动类型获取活动
    @GetMapping("/getActivitiesByType")
    public List<Activities> getActivitiesByType(@RequestHeader("Authorization") String token, @RequestParam("type") String type){
        token=token.substring(7).trim();
        if(jwtUtilsService.verifyToken(token)) {//验证用户token
            List<Activities> resultList = new ArrayList<>();
            activitiesService.list().forEach(activities -> {
                if(activities.getType().equals(type)&&activities.getAuditStatus().equals("审核通过")) //将满足要求的活动加入返回的信息列表
                    resultList.add(activities);
            });
            return resultList;
        }
        else return null;
    }

    //根据活动名模糊搜索
    @GetMapping("/search")
    public List<Activities> searchActivities(@RequestHeader("Authorization") String token, @RequestParam("keyWord") String keyWord){
        token=token.substring(7).trim();
        List<Activities> resultList = new ArrayList<Activities>();
        if(jwtUtilsService.verifyToken(token)) {
            activitiesService.searchActivities(keyWord).forEach(activities -> {
                if(activities.getAuditStatus().equals("审核通过"))
                    resultList.add(activities);
            });
           return resultList;
        }else return null;
    }

    //审核活动
    @PutMapping("/auditActivity")
    public boolean auditActivity(@RequestHeader("Authorization") String token,@RequestBody Map<String,String> map){
        token=token.substring(7).trim();
        if(jwtUtilsService.verifyToken(token)&&jwtUtilsService.parseToken(token).getPayload().get("UserRole").equals("管理员")) {//验证token是否有效以及用户权限
            String activityID = map.get("ActivityID");//获取从前端提交的活动ID
            String status = map.get("Status");//获取从前端提交的变更后的审核状态
            return activitiesService.auditActivity(activityID,status)>0;//执行审核状态的修改操作，若受影响行数大于一说明成功修改
        } else return false;
    }

    //修改活动信息
    @PutMapping("/updateActivityInfo")
    public boolean updateActivityInfo(@RequestHeader("Authorization") String token,@RequestBody Activities activities){
        token=token.substring(7).trim();
        boolean flag = getActivityById(activities.getActivityId()).get(("organizerId")).equals(jwtUtilsService.parseToken(token).getPayload().get("UserID"));
        if(jwtUtilsService.verifyToken(token)&&(flag||jwtUtilsService.parseToken(token).getPayload().get("UserRole").equals("管理员"))) {
           return activitiesService.updateActivitySelective(activities)>0;
        }else return false;
    }

    //退出活动
    @DeleteMapping("/exitActivity")
    public boolean exitActivity(@RequestHeader("Authorization") String token,@RequestParam("id") String activityId){
        token=token.substring(7).trim();
        if(jwtUtilsService.verifyToken(token)) {
            return registrationsService.exitActivity(jwtUtilsService.parseToken(token).getPayload().get("UserID").toString(),activityId)>0;
        }else return false;
    }

    //删除活动
    @DeleteMapping("/deleteActivity")
    public boolean deleteActivity(@RequestHeader("Authorization") String token,@RequestParam("id") String activityId){
        token=token.substring(7).trim();
        boolean flag = activitiesService.getById(activityId).getOrganizerId().equals(jwtUtilsService.parseToken(token).getPayload().get("UserID"));
        if(jwtUtilsService.verifyToken(token)&&(flag||jwtUtilsService.parseToken(token).getPayload().get("UserRole").equals("管理员"))) {
            return registrationsService.deleteByActivityId(activityId)>0||activitiesService.removeById(activityId);
        }else return false;
    }

    //获取活动信息并加入参与人数信息
    private Map<String,String> getActivityMap(Activities activities){
        Map<String,String> activityMap = new HashMap<>();
        //将activities的内容全部复制
        activityMap.put("activityId",activities.getActivityId());
        activityMap.put("title",activities.getTitle());
        activityMap.put("type",activities.getType().toString());
        activityMap.put("organizerId",activities.getOrganizerId());
        activityMap.put("startTime",activities.getStartTime().toString());
        activityMap.put("endTime",activities.getEndTime().toString());
        activityMap.put("location",activities.getLocation());
        activityMap.put("recruitNum",activities.getRecruitNum().toString());
        activityMap.put("description",activities.getDescription());
        activityMap.put("auditStatus",activities.getAuditStatus().toString());
        activityMap.put("createTime",activities.getCreateTime().toString());
        activityMap.put("imgPath",activities.getImgPath());
        //查询当前activities的参与人数并插入
        activityMap.put("participantNum",registrationsService.getParticipantNum(activities.getActivityId()));
        return activityMap;
    }
}
